package com.newgoldcurrency.activities.main;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.collection.ArraySet;
import androidx.core.content.res.ResourcesCompat;
import androidx.fragment.app.Fragment;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.App;
import com.newgoldcurrency.R;
import com.newgoldcurrency.bean.VersionBean;
import com.newgoldcurrency.databinding.FragmentAboutBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;

import java.io.IOException;
import java.util.HashMap;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class AboutFragment extends Fragment {

    private MainActivity activity;
    private FragmentAboutBinding binding;
    private final ArraySet<Call> calls=new ArraySet<>();
    private int verCode=0;
    private VersionBean bean;

    @SuppressLint("SetTextI18n")
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        activity = (MainActivity) getActivity();
        binding = FragmentAboutBinding.inflate(inflater, container, false);
        String verName="1.0.0";
        try {
            PackageInfo p = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0);
            verCode= p.versionCode;
            verName= p.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        binding.versionVersion.setText("Current version:"+verName);
        binding.versionUpdateBtn.setOnClickListener(view -> {
            if (checkDoubleClick()){
                if (bean.version>verCode){
                    Tools.update(activity, bean.title, bean.content, bean.forcedUpdate, () -> {
                        SharedPreferences.Editor edit = App.sp.edit();
                        edit.putBoolean("notremaining", true);
                        edit.apply();
                    }, () -> startActivity(new Intent().setAction("android.intent.action.VIEW").setData(Uri.parse("https://play.google.com/store/apps/details?id=com.newgoldcurrency"))));
                }
            }

        });
        binding.versionWebsite.setOnClickListener(view -> {
            if (checkDoubleClick()){
                startActivity(new Intent(Intent.ACTION_VIEW).setData(Uri.parse("http://goldrr.com/")));
            }
        });
        HashMap<String, String> map=new HashMap<>();
        map.put("code",String.valueOf(verCode));
        Network.post(map, "homepage/getUpdateInfo", call -> {
            call.enqueue(new Callback() {
                @Override
                public void onFailure(@NonNull Call call, @NonNull IOException e) {
                    e.printStackTrace();
                }
                @Override
                public void onResponse(@NonNull Call call, @NonNull Response response) {
                    activity.runOnUiThread(() -> {
                        try {
                            JsonObject jo = JsonParser.parseString(Objects.requireNonNull(response.body()).string()).getAsJsonObject();
                            if (jo.get("message").getAsString().equals("Get updateInfo success")){
                                bean = new Gson().fromJson(jo.get("data"), VersionBean.class);
                                try{
                                    int verCode = activity.getPackageManager().getPackageInfo(activity.getPackageName(), 0).versionCode;
                                    if (bean.version>verCode){

                                        binding.versionUpdateBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.bg_button_gold_10,null));
                                        binding.versionNewversionFounded.setText("New version founded:"+bean.versionName);
                                        binding.versionDot.setVisibility(View.VISIBLE);

                                        if (bean.forcedUpdate){
                                            Tools.update(activity, bean.title, bean.content, true, () -> {
                                                SharedPreferences.Editor edit = App.sp.edit();
                                                edit.putBoolean("notremaining", false);
                                                edit.apply();
                                            }, () -> startActivity(new Intent().setAction("android.intent.action.VIEW").setData(Uri.parse("https://play.google.com/store/apps/details?id=com.newgoldcurrency"))));

                                        }
                                    }else{
                                        binding.versionUpdateBtn.setBackground(ResourcesCompat.getDrawable(getResources(), R.drawable.bg_button_gold_grey,null));
                                        binding.versionNewversionFounded.setText("Already the latest version");
                                        binding.versionDot.setVisibility(View.GONE);
                                    }
                                }catch (PackageManager.NameNotFoundException e) {
                                    e.printStackTrace();
                                }
                            }else{
                                Tools.toast(jo.get("message").getAsString());
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    });
                }
            });
            calls.add(call);
        });
        return binding.getRoot();
    }
    @Override
    public void onDestroyView() {
        super.onDestroyView();
        for (Call c :calls) c.cancel();
        binding=null;
    }
    private long mClickTime;
    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
}



